package com.newcoin.xgb.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newcoin.xgb.dto.QueryParameterDto;
import com.newcoin.xgb.dto.SendSmsCodeDto;
import com.newcoin.xgb.entity.*;
import com.newcoin.xgb.mapper.*;
import com.newcoin.xgb.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CommonServiceImpl implements CommonService {
    private static final String APPKEY = "47009207bf4bd1a3f46d2467dc2d835a";
    private static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
    //    private static String url = "http://v.juhe.cn/sms/send";
    private static String url = "http://api.smsbao.com/sms";


    @Value("${key}")
    private String key;

    @Value("${smsName}")
    private String smsName;

    @Value("${smsPwd}")
    private String smsPwd;

//   @Value("${smsUrl}")
//    private String url;

    @Value("${filePath}")
    private String filePath;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private AppVersionMapper appVersionMapper;

    @Autowired
    private IndexCarouselMapper indexCarouselMapper;

    @Autowired
    private IndexAnnMapper indexAnnMapper;

    @Autowired
    private CustomerServiceMapper customerServiceMapper;

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Override
    public Result sendSmsCode(SendSmsCodeDto sendSmsCodeDto) throws Exception {
        log.info("sendSmsCodeDto======{}", sendSmsCodeDto);
        String isSend = redisTemplate.opsForValue().get(sendSmsCodeDto.getMobile());
        if (StringUtils.isEmpty(isSend)) {
            if (sendSmsCodeDto.getKey().equalsIgnoreCase(DigestUtils.md5DigestAsHex(("Vhta6YpievbqRZIj02OAfxwMKWmFPSkc" + sendSmsCodeDto.getMobile()).getBytes()))) {

                Result result = new Result();
                String verifyCode = random();
                String testContent = "【hqrg】您的验证码为" + verifyCode + "，在5分钟内有效。"; // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如 测一下、您好。否则可能会收不到
                StringBuffer httpArg = new StringBuffer();
                httpArg.append("u=").append("18508208447").append("&");
                httpArg.append("p=").append(md5("aa123123")).append("&");
                httpArg.append("m=").append(sendSmsCodeDto.getMobile()).append("&");
                httpArg.append("c=").append(encodeUrlString(testContent, "UTF-8"));
//                MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
//                paramMap.add("mobile", sendSmsCodeDto.getMobile());
//                paramMap.add("key", APPKEY);
//                HttpHeaders headers = new HttpHeaders();
//                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//                headers.set("User-agent", userAgent);
//
//                paramMap.add("tpl_id", "227069");
//                paramMap.add("tpl_value", URLEncoder.encode("#code#=" + verifyCode, "UTF-8"));
//
//                HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity(paramMap, headers);
//                String str = restTemplate.postForObject(url, httpEntity, String.class);
//                Map<String, Object> resultMap = (Map<String, Object>) JSON.parse(str);
//                int resultStr = (int) resultMap.get("error_code");

                String resultStr = request(url, httpArg.toString());
                log.info("短信发送结果={}", resultStr);
                if (resultStr.equals("0")) {
                    redisTemplate.opsForValue().set("send" + sendSmsCodeDto.getMobile(), verifyCode, 300, TimeUnit.SECONDS);
                    redisTemplate.opsForValue().set(sendSmsCodeDto.getMobile(), "is", 58, TimeUnit.SECONDS);
                    result.setMessage("短信发送成功");
                    result.setCode(200);
                    return result;
                } else {
                    throw new RuntimeException("发送失败");
                }
            }
        }
        return null;
    }

    @Override
    public Result uploadFile(MultipartFile multipartFile, String type) throws Exception {
        log.info("file={},type={}", multipartFile, type);
        Result result = new Result();
        long fileName = System.currentTimeMillis();
        String originalFileName = multipartFile.getOriginalFilename();
        String suffix = originalFileName.substring(originalFileName.lastIndexOf(".") + 1).toLowerCase();
        if (!suffix.equals("jpg") && !suffix.equals("png") && !suffix.equals("jpeg")) {
            result.setMessage("非法文件");
            result.setCode(500);
            return result;
        }
        File file = new File(filePath + "/" + type);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
        File file1 = new File(filePath + "/" + type + "/" + fileName + "." + suffix);
        multipartFile.transferTo(file1);
        result.setCode(200);
        result.setMessage("/static/" + type + "/" + fileName + "." + suffix);
        return result;
    }

    /***
     * 检查更新
     * @param version
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> isUpdate(String version) throws Exception {
        log.info("检查更新入参 version={}", version);
        NewCoinAppVersion appVersion = commonMapper.getAppVersionInfo();
        log.info("NewCoinAppVersion={}", appVersion);
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        map.put("status", 0);
        if (!version.equalsIgnoreCase(appVersion.getVersion())) {
            if (appVersion.getStatus() == 0) {
                data.put("status", 1);
                data.put("note", appVersion.getRemark());
                data.put("url", appVersion.getWgetUrl());
                map.put("status", 1);
                map.put("msg", "查询更新种");
                map.put("data", data);
                log.info("热更新");
            } else if (appVersion.getStatus() == 1) {
                data.put("status", 1);
                data.put("note", appVersion.getRemark());
                data.put("url", appVersion.getAppUrl());
                map.put("status", 1);
                map.put("msg", "查询更新种");
                map.put("data", data);
                log.info("整包更新");
            }
            return map;
        }
        data.put("status", 0);
        map.put("status", 1);
        map.put("msg", "查询更新种");
        map.put("data", data);
        return map;
    }

    @Override
    public Result<List<XgbIndexCarousel>> getCarousel() throws Exception {
        Result<List<XgbIndexCarousel>> result = new Result<>();
        List<XgbIndexCarousel> xgbIndexCarousel = indexCarouselMapper.selectList(new QueryWrapper<>());
        result.setCode(200);
        result.setMessage("成功");
        result.setData(xgbIndexCarousel);
        return result;
    }

    @Override
    public Result<List<XgbArea>> getArea() throws Exception {
        Result<List<XgbArea>> result = new Result<>();
        List<XgbArea> xgbAreas = areaMapper.selectList(new QueryWrapper<>());
        result.setCode(200);
        result.setMessage("成功");
        result.setData(xgbAreas);
        return result;
    }

    @Override
    public Result<List<XgbIndexAnn>> getAnnouncement() throws Exception {
        Result<List<XgbIndexAnn>> result = new Result<>();
        List<XgbIndexAnn> xgbIndexAnns = indexAnnMapper.selectList(new QueryWrapper<XgbIndexAnn>()
                .eq("state", 0)
                .orderByDesc("create_date"));
        result.setData(xgbIndexAnns);
        result.setMessage("成功");
        result.setCode(200);
        return result;
    }

    @Override
    public Result<XgbIndexAnn> getAnnouncementBuyId(QueryParameterDto queryParameterDto) throws Exception {
        Result<XgbIndexAnn> result = new Result<>();
        XgbIndexAnn indexAnn = indexAnnMapper.selectById(queryParameterDto.getId());
        result.setData(indexAnn);
        result.setMessage("成功");
        result.setCode(200);
        return result;
    }

    @Override
    public Result<XgbCustomerService> getCustomerService() throws Exception {
        Result result = new Result();
        XgbCustomerService xgbCustomerService = customerServiceMapper.selectById(1);
        result.setData(xgbCustomerService);
        result.setMessage("成功");
        result.setCode(200);
        return result;
    }

    /**
     * 生成验证码
     *
     * @return
     */
    private String random() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    }


    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = reader.readLine();
            if (strRead != null) {
                sbf.append(strRead);
                while ((strRead = reader.readLine()) != null) {
                    sbf.append("\n");
                    sbf.append(strRead);
                }
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String md5(String plainText) {
        StringBuffer buf = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    public static String encodeUrlString(String str, String charset) {
        String strret = null;
        if (str == null)
            return str;
        try {
            strret = java.net.URLEncoder.encode(str, charset);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return strret;
    }

//    public static void main(String[] args) {
//        System.out.println(DigestUtils.md5DigestAsHex("Vhta6YpievbqRZIj02OAfxwMKWmFPSkc13913247545".getBytes()));
//    }
}
